<template>
  <div class="role-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色权限管理</span>
          <el-button type="primary" @click="handleAdd">新增角色</el-button>
        </div>
      </template>

      <!-- 角色列表 -->
      <el-table v-loading="loading" :data="roleList" style="width: 100%">
        <el-table-column prop="name" label="角色名称" width="180" />
        <el-table-column prop="code" label="角色编码" width="180" />
        <el-table-column
          prop="description"
          label="角色描述"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === "active" ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button
                type="success"
                size="small"
                @click="handlePermission(row)"
              >
                权限
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑角色' : '新增角色'"
      width="500px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input
            v-model="form.code"
            placeholder="请输入角色编码"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="form.status"
            :active-value="'active'"
            :inactive-value="'inactive'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog v-model="permissionDialogVisible" title="权限分配" width="600px">
      <el-tree
        ref="permissionTree"
        :data="permissionList"
        :props="defaultProps"
        show-checkbox
        node-key="id"
        :default-checked-keys="checkedPermissions"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePermissions">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

// 表格数据
const loading = ref(false);
const roleList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 表单对话框
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref(null);
const form = reactive({
  name: "",
  code: "",
  description: "",
  status: "active",
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入角色编码", trigger: "blur" }],
};

// 权限树对话框
const permissionDialogVisible = ref(false);
const permissionTree = ref(null);
const currentRole = ref(null);
const permissionList = ref([]);
const checkedPermissions = ref([]);
const defaultProps = {
  children: "children",
  label: "name",
};

// 获取角色列表
const getRoleList = () => {
  loading.value = true;
  // 实现获取角色列表的逻辑
  loading.value = false;
};

// 获取权限树数据
const getPermissionTree = () => {
  // 实现获取权限树数据的逻辑
};

// 新增角色
const handleAdd = () => {
  isEdit.value = false;
  form.name = "";
  form.code = "";
  form.description = "";
  form.status = "active";
  dialogVisible.value = true;
};

// 编辑角色
const handleEdit = (row) => {
  isEdit.value = true;
  Object.assign(form, row);
  dialogVisible.value = true;
};

// 删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm("确认删除该角色吗？删除后无法恢复。", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      // 实现删除角色的逻辑
      ElMessage.success("删除成功");
      getRoleList();
    } catch (error) {
      console.error("删除失败：", error);
      ElMessage.error("删除失败");
    }
  });
};

// 打开权限分配对话框
const handlePermission = (row) => {
  currentRole.value = row;
  checkedPermissions.value = row.permissions || [];
  permissionDialogVisible.value = true;
  getPermissionTree();
};

// 保存权限分配
const savePermissions = async () => {
  try {
    const checkedKeys = permissionTree.value.getCheckedKeys();
    const halfCheckedKeys = permissionTree.value.getHalfCheckedKeys();
    const permissions = [...checkedKeys, ...halfCheckedKeys];

    // 实现保存权限的逻辑

    ElMessage.success("保存成功");
    permissionDialogVisible.value = false;
  } catch (error) {
    console.error("保存失败：", error);
    ElMessage.error("保存失败");
  }
};

// 提交表单
const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        // 实现提交表单的逻辑
        const message = isEdit.value ? "编辑成功" : "新增成功";
        ElMessage.success(message);
        dialogVisible.value = false;
        getRoleList();
      } catch (error) {
        console.error("保存失败：", error);
        ElMessage.error("保存失败");
      }
    }
  });
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  getRoleList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getRoleList();
};

// 页面加载时获取数据
getRoleList();
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
